package com.ymh.dao.impl;

import com.ymh.dao.StudentDao;
import com.ymh.entity.Student;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * StudentDao访问接口实现类：通过Spring JDBC的方式操作
 * Created by aivin on 2018/8/10.
 */
public class StudentDaoSpringJdbcImpl implements StudentDao {

    private JdbcTemplate jdbcTemplate;


    @Override
    public List<Student> query() {
        final List<Student> list = new ArrayList<>();
        String sql = "select id,name,age,gander,flag from student";
        jdbcTemplate.query(sql, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                Student student = new Student();
                Long id = resultSet.getLong("id");
                student.setId(id);
                String name = resultSet.getString("name");
                student.setName(name);
                Integer age = resultSet.getInt("age");
                student.setAge(age);
                String gander = resultSet.getString("gander");
                student.setGander(gander);
                String flag = resultSet.getString("flag");
                student.setFlag(flag);
                list.add(student);
            }
        });
        return list;
    }

    @Override
    public void save(Student student) {
        String sql = " insert into student(name,age,gander,flag) values(?,?,?,?)";
        jdbcTemplate.update(sql, new Object[]{student.getName(), student.getAge(), student.getGander(), student.getFlag()});
    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

}
